<?php

class GetProductDetail extends Controller
{
	/**
	 * construct function
	 */
	public function __construct()
	{
		parent::__construct();
		header('Cache-Control: no-store, no-cache, must-revalidate');
		require_once('system/libraries/currency.php');
		$this->obj_currency = new Currency();
	}
	
	/**
	 * Page generate function link the index page entrance.
	 * @param null
	 * @Return null
	 */
	public function run()
	{
		if (!$_POST)
		{
			$str  = $this->generateProductDetail();
			echo $str;
		}
		else
		{
			$str  = $this->getProductAttrs();
			echo $str;exit;
		}
	}
	
	/**
	 * Get product attributes
	 * @param null
	 * @return string
	 */
	private function getProductAttrs()
	{
		$this->import("Database");
		
		if ($_POST['act'] == 'getQuantity')
		{
			if (!isset($_POST['id_size']) || !$_POST['id_size'])
				$condition = "`id_catalog`=".$_GET['id']." AND `id_color`=".$_POST['id_colour'];
			else
				$condition = "`id_catalog`=".$_GET['id']." AND `id_color`=".$_POST['id_colour']." AND `id_size`=".$_POST['id_size'];
					
			$obj_catalog_attributes = $this->Database->prepare("SELECT * FROM `tl_catalog_attribute` WHERE $condition")
													->execute(time(),time());
			
			if ($obj_catalog_attributes->numRows < 1)
			{
				return '{"res":"error","html":"<span>Out of stock. <a href=\"mailto:info@daftshopping.com?subject=Out of stock-'.$_POST["skuid"].'-' . $_POST["prodcut_name"] . '\" title=\"email me\" style=\"color:White;\"><u>Email me</u></a> when this item becomes available.</span>"}';
			}
			else
			{
				if ($obj_catalog_attributes->catalog_stock == 0)
					return '{"res":"error","html":"<span>Out of stock. <a href=\"mailto:info@daftshopping.com?subject=Out of stock-'.$_POST["skuid"].'-' . $_POST["prodcut_name"] . '\" title=\"email me\" style=\"color:White;\"><u>Email me</u></a> when this item becomes available.</span>"}';
				else
				{
					$str_html = '<strong>QUANTITY</strong>: <select id=\'quantity\' name=\'quantity\'><option value=\'\'>- SELECT QUANTITY -</option>';
					if ($obj_catalog_attributes->catalog_stock >= 10)
						$cnt = 10;
					else
						$cnt = intval($obj_catalog_attributes->catalog_stock);
					for ($i=1;$i<=$cnt;$i++)
					{
						$str_html .= "<option" . (($i == 1) ? " selected=\'selected\'" : "") . " value=\'".$i."\'>".$i."</option>";
					}
					$str_html .= "</select>";
					
					return '{"res":"success","html":"'.$str_html.'"}';
				}
			}
		}
		else
		{
			$obj_catalog_attributes = $this->Database->prepare("SELECT ca_size.id, ca_size.size  
																FROM `tl_catalog_attribute` AS attr
																INNER JOIN `catalog_size` AS ca_size ON ca_size.`id`=attr.`id_size` 
																WHERE attr.`id_catalog`=? AND attr.`id_color`=?")
													->execute($_GET['id'],$_POST['id_colour']);
													
			if ($obj_catalog_attributes->numRows < 1)
			{
				return '{"res":"error","html":"<span>Out of stock. <a href=\"mailto:info@daftshopping.com?subject=Out of stock-'.$_POST["skuid"].'-' . $_POST["prodcut_name"] . '\" title=\"email me\" style=\"color:White;\"><u>Email me</u></a> when this item becomes available.</span>"}';
			}
			else
			{
				$str_html = '<strong>SIZE</strong>: <select id=\'size\' name=\'size\'><option selected=\'selected\' value=\'\'>- SELECT SIZE -</option>';
				$index = 0;
				while ($obj_catalog_attributes->next())
				{
					$str_html .= "<option value='".$obj_catalog_attributes->id."'>".$obj_catalog_attributes->size."</option>";
				}
				$str_html .= "</select>";
				
				return '{"res":"success","html":"'.$str_html.'"}';
			}
		}
	}
	
	/**
	 * Get a special product page html by category id and product id
	 * @param null
	 * @Return html string.
	 */
	public function generateProductDetail()
	{
		$objRd		= $this->getProductDetailPage();
		
		if (!isset($objRd) || !$objRd)
			return '<div id="product_detail"><strong>This product\'s attribute is not defined or product is not existent.</strong></div>';
			
		if (!isset($objRd['published']) || !$objRd['published'])
			return '<div id="product_detail"><strong>We are sorry the product is sold out.</strong></div>';
		
		$colours	= $this->getColour();
		$tags		= $this->getTag();
		$sizes		= $this->getSize();
		$breadcrumb = $this->getBreadcrumb();
		$shareurl = urlencode($_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
		$_shipping_html = $this->getShippings($objRd['programe']);
		
		// get Tags
		if($objRd['tags']==""){
			$tagHTML = "";
		}else{
			$tagIDs = explode(",", $objRd['tags']);
			$tagHTML= "";
			for($i=0;$i<count($tagIDs);$i++){
				$key  	  = $tagIDs[$i];
				$tagHTML .= '<a href="./?tag='.$key.'&type=all" title="View more '.$tags[$key]['tag'].'">View more '.$tags[$key]['tag'].'</a> | ';
			}
			$tagHTML = substr($tagHTML, 0, -2);	
			$tagHTML = '<p class="more">'.$tagHTML.'</p>';
		}

		// get Colour
		//$colourIDs = explode(",", $objRd['colour']);
		$is_out_of_stock = false;
		if (isset($objRd['colour']))
		{
			$colourIDs = array_keys($objRd['colour']);
			$strColourIDs = implode(',', array_keys($objRd['colour']));
			$colourHTML= "<input type=\"hidden\" name=\"selected_id_colour\" value=\"".$colourIDs[0]."\" />";
			for($i=0;$i<count($colourIDs);$i++){
				$key  = $colourIDs[$i];
				//$colourHTML .= "<a href='product.html?category=".$objRd['category']."&id=".$objRd['id']."&id_colour=".$key."#product_detail'><img src=\"".$colours[$key]['img']."\" alt=\"".$colours[$key]['title']."\" /></a>";
				$colourHTML .= "<a href='javascript:void(0);' id_colour=\"".$key."\" colour_title=\"".$colours[$key]['title']."\" title=\"select colour\"><img src=\"".$colours[$key]['img']."\" alt=\"".$colours[$key]['title']."\" /></a>";
			}
		
			// set Images
			$colourPath = "daft_files/catalog/products/".$objRd['skuid']."/";
			if(isset($_GET['id_colour']) && $_GET['id_colour']!=""){
				$colour = $colours[$_GET['id_colour']]['title'];
			}else{
				foreach ((array)$objRd['attribute'] as $arr)
				{
					if ($arr['stock'] > 0)
					{
						$colour = $arr['colour'];
						break;
					}
				}
				if (!$colour)
				{
					$colour = $objRd['attribute'][0]['colour'];
					$is_out_of_stock = true;
				}
				$colour = $colours[$colour]['title'];
			}
			$colourPath .= $colour."/";
			
			$imgsHTML = "";
			for($i=1;$i<=8;$i++){
				$filename = $colourPath.$i.".jpg";
				if(file_exists($filename)) $imgsHTML .= '<li><a href="javascript:void(0);" onClick=\'selectedPic("'.$i.'","'.$colourPath.'");return false;\' title=""><img src="image.php?src='.$filename.'&width=93&height=93" alt="'.$objRd['name'].'"/></a></li>';
			}
			
			// get Size
			if(isset($_GET['id_colour']) && $_GET['id_colour']!="" && isset($objRd['colour'][$_GET['id_colour']]))
			{			
				//$sizeIDs = $objRd['colour'][$_GET['id_colour']]['size'];	
				$default_color = $_GET['id_colour'];
				$sizeIDs = array_keys($objRd['colour'][$_GET['id_colour']]);
				//$strSizeIDs = implode(',', $objRd['colour'][$_GET['id_colour']]['size']);
				$strSizeIDs = implode(',', array_keys($objRd['colour'][$_GET['id_colour']]));
				$sizeHTML = '<option value="">- SELECT SIZE -</option>';
				for($i=0;$i<count($sizeIDs);$i++){
					$key  	  = $sizeIDs[$i];
					if (isset($_GET['id_size']) && $_GET['id_size'] != "")
					{
						$default_size = $_GET['id_size'];
						if ($key == $_GET['id_size'])
							$sizeHTML .= '<option value="'.$key.'" selected="selected">'.$sizes[$key]['size'].'</option>';
						else
							$sizeHTML .= '<option value="'.$key.'">'.$sizes[$key]['size'].'</option>';
					}
					else
					{
						if (!$default_size && $objRd['colour'][$_GET['id_colour']][$key][0])
						{
							$default_size = $sizes[$key]['size'];
							$sizeHTML .= '<option value="'.$key.'" selected="selected">'.$sizes[$key]['size'].'</option>';
						}
						else
							$sizeHTML .= '<option value="'.$key.'">'.$sizes[$key]['size'].'</option>';
					}
				}
				
			}
			else
			{
				//$sizeIDs = $objRd['colour'][$colourIDs[0]]['size'];
				foreach ((array)$objRd['attribute'] as $arr)
				{
					if ($arr['stock'] > 0)
					{
						$default_color = $arr['colour'];
						break;
					}
				}
				if (!$default_color)
				{
					$default_color = $objRd['attribute'][0]['colour'];
					$is_out_of_stock = true;
				}
				$sizeIDs = array_keys($objRd['colour'][$default_color]);
				//$strSizeIDs = implode(',', $objRd['colour'][$colourIDs[0]]['size']);
				$strSizeIDs = implode(',', array_keys($objRd['colour'][$default_color]));
				$sizeHTML = '<option value="">- SELECT SIZE -</option>';
				for($i=0;$i<count($sizeIDs);$i++){
					$key  	  = $sizeIDs[$i];
					if (isset($_GET['id_size']) && $_GET['id_size'] != "")
					{
						$default_size = $_GET['id_size'];
						if ($key == $_GET['id_size'])
							$sizeHTML .= '<option value="'.$key.'" selected="selected">'.$sizes[$key]['size'].'</option>';
						else
							$sizeHTML .= '<option value="'.$key.'">'.$sizes[$key]['size'].'</option>';
					}
					else
					{
						if ((!$default_size && $objRd['colour'][$default_color][$key][0] > 0) || ($i==0 && $is_out_of_stock))
						{
							$default_size = $key;
							
							$sizeHTML .= '<option value="'.$key.'" selected="selected">'.$sizes[$key]['size'].'</option>';
						}
						else
							$sizeHTML .= '<option value="'.$key.'">'.$sizes[$key]['size'].'</option>';
					}
				}
			}
			//$sizeIDs = explode(",", $objRd['size']);
		}
		else
		{
			// set Images
			$colourPath = "daft_files/catalog/products/".$objRd['skuid']."/";
			$colourPath .= $colours[$objRd['attribute'][0]['colour']]['title']."/";
			
			$imgsHTML = "";
			for($i=1;$i<=4;$i++){
				$filename = $colourPath.$i.".jpg";
				if(file_exists($filename)) $imgsHTML .= '<li><a href="#" onClick=\'selectedPic("'.$i.'","'.$colourPath.'");return false;\' title=""><img src="image.php?src='.$filename.'&width=93&height=93" alt="'.$objRd['name'].'"/></a></li>';
			}
		}
		
		$strHTML = '
<div id="product_detail">
	<form name="productform" method="post" action="product.html?category='.$objRd['category'].'&id='.$objRd['id'].'#product_detail">
	<input type="hidden" value="addtocart" name="FORM_SUBMIT"/>
	<input type="hidden" value="'.$objRd['id'].'" name="id"/>
	<input type="hidden" value="'.$objRd['skuid'].'" name="skuid"/>
	<input type="hidden" value="'.$objRd['name'].'" name="prodcut_name"/>
	<input type="hidden" value="'.$objRd['price'].'" name="price"/>
	<input type="hidden" value="'.$colour.'" name="colour"/>
	<input type="hidden" value="'.$strColourIDs.'" name="colour_ids"/>
	<input type="hidden" value="'.$strSizeIDs.'" name="size_ids"/>
	<input type="hidden" value="'.((isset($_GET['id_size']) && $_GET['id_size'] != "") ? $_GET['id_size'] : '') .'" name="id_size"/>
	<div class="gallery">
		'.$tagHTML.'
		<div id="big_pics" class="pic">
			<a href="'.$colourPath.'big/1.jpg" class="jqzoom" id="bImg" title="'.$objRd['name'].'"><img src="'.$colourPath.'1.jpg"  id="mImg" title="'.$objRd['name'].'"></a>
		</div>
		<ul class="thumb" id="pic_thumbs">
			'.$imgsHTML.'
		</ul>
		<span class="product_zoom"></span>
		<a href="Tell_friend.html" title="Tell Friend" class="tell_friend iframe2">Tell Friend</a>
		'.$breadcrumb.'
	</div>
	
	<div class="property">
		<h2>'.$objRd['name'].'</h2>
		<span class="order">'.$objRd['skuid'].'</span>
		<span class="price">'.$this->obj_currency->change_order($objRd['price']).(($objRd['sales']) ? '&nbsp;<span style="color:#999; font-size:12px;">' . $this->obj_currency->change_iso_order($objRd['wasprice']) : '') . '</span></span>
		<!--产品滑动js-->
		<script type="text/javascript">
			jQuery(function(){
				jQuery("#detailtab").click(function(el){
					var _current_tags = $(el.target);
					var _current_id = _current_tags.attr("title");
					if (_current_tags.attr("id") != "" && _current_tags.attr("id") == "more_shipping_detail") return;
					if (_current_id){
						if (jQuery("#"+_current_id)){
							jQuery("#detailtab .cons").hide();
							jQuery("#"+_current_id).show();
						}
						_current_tags.parent("li").parent("ul").find("a").removeClass("selected");
						_current_tags.addClass("selected");
					}
					return false;
				});
			});
		</script>
		<div id="detailtab">			
			<ul class="tab">
				<li><a href="javascript:void(0);" title="tab_overview" class="selected">OVERVIEW</a></li>
				<li><a href="javascript:void(0);" title="tab_details">DETAILS</a></li>
				<li><a href="javascript:void(0);" title="tab_shipping">SHIPPING</a></li>
			</ul>
			<div id="tab_overview" class="cons">
				<div class="hdproduct">
					' . $objRd['description'] . '
				</div>
			</div>
			<div  class="cons" id="tab_details" style="display: none;">
				<div class="hdproduct">
					'.$objRd['overview'].'
				</div>
			</div>
			<div  class="cons" id="tab_shipping" style="display: none;">
				' . $_shipping_html . '
			</div>
		</div>
		<div class="product_extra">
			<div id="tool">
				<script type="text/javascript">jQuery(function(){
					jQuery("#slip").click(function(){
						
						jQuery("#add_tocart_success").hide();
						jQuery("#add_tocart_faliure").hide();
						if (jQuery("select[@name=\'size\']").val() != "")
						{
							jQuery("#add_tocart_error").hide();
							
							jQuery.ajax({
								 type: "POST",
								 url: "saveBackPocket.php",
								 data: "catalogid=" + jQuery("input[@name=\'id\']").val() + "&size=" + jQuery("select[@name=\'size\']").val() + "&color=" + jQuery("input[@name=\'colour\']").val() + "&quantity=" + jQuery("select[@name=\'quantity\']").val() + "&gift_wrapping=" + jQuery("input[@name=\'gift_wrapping\'][@checked]").val() + "&gwPrice=" + jQuery("input[@name=\'gwPrice\']").val(),
								 success: function(msg){ 
									//alert( "Data Saved: " +   msg );
									if (msg == \'false\')
									{
										//alert(msg);
										window.location = "backpocket.html";
									}
									else
									{
										jQuery("#add_to_backprocket").show();
										//window.location = "backpocket.html";
									}
								} 
							});
							
							return false;
						}
						else
						{
							jQuery("#add_tocart_error").show();
							return false;
						}
					});
					
					var _btn_submits = "";
					if (jQuery("p.submits").attr("class") != undefined)
						_btn_submits = jQuery("p.submits");
					else
						_btn_submits = jQuery("p.submits_continue");
					_btn_submits.find("a.checkout").click(function(el){
							var _target = jQuery(el.target)||jQuery(el);
							if (_target.attr("disabled") != "" && _target.attr("disabled") == "true") return false;
							
							jQuery("#add_tocart_success").hide();
							jQuery("#add_tocart_faliure").hide();
							if (jQuery("select[@name=\'size\']").val() != "")
							{
								if (jQuery("select[@name=\'quantity\']").val() != ""){
									jQuery("#add_tocart_error").hide();
									jQuery("input[@name=\'FORM_SUBMIT\']").val(\'checkout\');
									jQuery("form[name=\'productform\']").submit();
								}else{
									jQuery("#add_tocart_error").html("<span class=\"error\">Please select quantity.</span>");
									jQuery("#add_tocart_error").show();
								}
							}
							else
							{
								jQuery("#add_tocart_error").html("<span class=\"error\">Please select the size.</span>");
								jQuery("#add_tocart_error").show();
							}
							
							return false;
					});
					
					var detail_change_fn = function(el){
						var _target = $(el.target) || $(el);
						if (_target.attr("id") != "size")
							return false;
						
						jQuery("input[@name=\'id_size\']").val(jQuery("select[@name\'size\']").val());
						var url = window.location.href;
						jQuery(".error").hide();
						if (jQuery("select[@name=\'size\']").val() != "")
						{
							var prev_url = "";
							var suf_url = "";
							if (url.indexOf("#product_detail") > -1)
							{
								if (url.indexOf("&add_tocart=") > -1)
								{
									prev_url = url.substring(0, url.indexOf("&add_tocart="));
									suf_url = url.substring(url.indexOf("&add_tocart=")+12, url.length);
									if (suf_url.indexOf("&") > -1)
										suf_url = suf_url.substring(suf_url.indexOf("&"), suf_url.length);
									url = prev_url + suf_url;
								}
								if (url.indexOf("&id_size=") > -1)
									url = url.substring(0, url.indexOf("&id_size="));
								else
									url = url.substring(0, url.indexOf("#product_detail"));
							}
							else
							{
								if (url.indexOf("&add_tocart=") > -1)
								{
									prev_url = url.substring(0, url.indexOf("&add_tocart="));
									suf_url = url.substring(url.indexOf("&add_tocart=")+12, url.length);
									if (suf_url.indexOf("&") > -1)
										suf_url = suf_url.substring(suf_url.indexOf("&"), suf_url.length);
									url = prev_url + suf_url;
								}
								
								if (url.indexOf("#") > -1 && url.indexOf("#product_detail") < 0)
									url = url.substring(0, url.indexOf("#"));
							}
							
							//window.location.href = url + "&id_size=" + jQuery("select[@name=\'size\']").val() + "#product_detail";
							$.ajax({
								 type: "POST",
								 url: url,
								 data: "act=getQuantity&id_colour="+jQuery("input[@name=\'selected_id_colour\']").val()+"&id_size="+jQuery("select[@name=\'size\']").val()+"&skuid="+jQuery("input[@name=\'skuid\']").val()+"&prodcut_name="+jQuery("input[@name=\'prodcut_name\']").val(),
								 dataType:"json",
								 beforeSend: function(){ 
									$("#load_div").show(); 
								},
								 success: function(msg){ 
									if (msg.res=="error"){
										$("#add_tocart_error").addClass("error");
										_btn_submits.find("a.addcart").attr("disabled","true");
										_btn_submits.find("a.checkout").attr("disabled","true");
										$("#add_tocart_error").show();
										$("#add_tocart_error").html(msg.html);
									}else{
										$("#add_tocart_error").removeClass("error");
										_btn_submits.find("a.addcart").removeAttr("disabled");
										_btn_submits.find("a.checkout").removeAttr("disabled");
										$("#add_tocart_error").hide();
										$("#detail_quantity").html(msg.html);
									}
									$("#detail_quantity").show();
									$("#add_to_backprocket").hide();
									$("#load_div").hide();
									jQuery("input[@name=\'id_size\']").val(jQuery("select[@name=\'size\']").val());
								} 
							});
						}
						else
						{
							if (url.indexOf("&id_size=") > -1)
								url = url.substring(0, url.indexOf("&id_size="));
							else
								url = url.substring(0, url.indexOf("#product_detail"));
							
							$.ajax({
								 type: "POST",
								 url: url,
								 data: "act=getQuantity&id_colour="+jQuery("input[@name=\'selected_id_colour\']").val()+"&id_size="+jQuery("select[@name=\'size\']").val()+"&skuid="+jQuery("select[@name=\'skuid\']").val()+"&prodcut_name="+jQuery("input[@name=\'prodcut_name\']").val(),
								 dataType:"json", 
								 beforeSend: function(){ 
									$("#load_div").show(); 
								},
								 success: function(msg){ 
									if (msg.res=="error"){
										$("#detail_quantity").addClass("error");
										_btn_submits.find("a.addcart").attr("disabled","true");
										_btn_submits.find("a.checkout").attr("disabled","true");
									}else{
										$("#detail_quantity").removeClass("error");
										_btn_submits.find("a.addcart").removeAttr("disabled");		
										_btn_submits.find("a.checkout").removeAttr("disabled");
									}
									$("#detail_quantity").show();
									$("#add_to_backprocket").hide();
									$("#load_div").hide(); $("#detail_quantity").html(msg.html); 
								} 
							});
							//window.location.href = url;
						}
					};
					jQuery("#detail_size").find("select").change(detail_change_fn);
					
					jQuery(".select_color").find("a").click(function(el){
						var _target = $(el.target) || $(el);
						var _url = window.location.href;
						var _id_colour = _target.parent("a").attr("id_colour");
						var _colour_title = _target.parent("a").attr("colour_title");
						jQuery("input[@name=\'colour\']").val(_colour_title);
						jQuery("input[@name=\'selected_id_colour\']").val(_id_colour);
						jQuery(".error").hide();
						$.ajax({
							 type: "POST",
							 url: _url,
							 data: "act=getSize&id_colour="+_id_colour+"&skuid="+jQuery("select[@name=\'skuid\']").val()+"&prodcut_name="+jQuery("input[@name=\'prodcut_name\']").val(),
							 beforeSend: function(){ 
								$("#load_div").show(); 
							},
							dataType:"json", 
							success: function(msg){ 							
								if (msg.res=="error"){
									$("#detail_quantity").addClass("error");
								}else{
									$("#detail_quantity").removeClass("error");
									$("#detail_quantity").show();
								}
								var _a = "", 
								_img = "", 
								_html = "", 
								_src = "", 
								_src_new = "", 
								_length = "", 
								_onclick = "", 
								_onclick_new = ""; 
								$("#pic_thumbs").find("li").each(function(index, item){
									_src_new = "";
									_onclick_new = "";
									_a = $(item).find("a");
									_img = $(_a[0]).find("img");
									_src = _img.attr("src").split("/");
									_length = _src.length;
									_src[_length-2] = _colour_title;
									for (i in _src)
									{
										_src_new += _src[i] + "/";
									}
									_src_new = _src_new.substr(0,_src_new.length-1);
									_img.attr("src", _src_new);
									_src_new = _src_new.split("?");
									_src_new = _src_new[1];
									_src_new = _src_new.split("&");
									_src_new = _src_new[0];
									_src_new = _src_new.split("=");
									_src_new = _src_new[1];
									_src_new = _src_new.substr(0,_src_new.lastIndexOf("/")+1);
									$(_a[0]).removeAttr("onclick")
									$(_a[0]).click(function(){
										selectedPic(index+1,_src_new);
										return false;
									});
								});
								var _big_image_a = jQuery("#big_pics").find("a");
								var _big_image_href = _big_image_a.attr("href");
								_big_image_href = _big_image_href.split("/");
								var _big_image_img = jQuery("#big_pics").find("img");
								_big_image_href[_big_image_href.length-3] = _colour_title;
								var _big_image_href_new = "";
								for (i in _big_image_href)
								{
									_big_image_href_new += _big_image_href[i] + "/";
								}
								_big_image_href_new = _big_image_href_new.substr(0,_big_image_href_new.length-1);
								_big_image_a.attr("href",_big_image_href_new);
								
								var _big_image_img_src = _big_image_img.attr("src");
								_big_image_img_src = _big_image_img_src.split("/");
								_big_image_img_src[_big_image_img_src.length-2] = _colour_title;
								var _bing_image_img_src_new = "";
								for (i in _big_image_img_src)
								{
									_bing_image_img_src_new += _big_image_img_src[i] + "/";
								}
								_bing_image_img_src_new = _bing_image_img_src_new.substr(0,_bing_image_img_src_new.length-1);
								_big_image_img.attr("src",_bing_image_img_src_new);
								$("#detail_size").html(msg.html); $("#detail_quantity").html("");
								$("#detail_size").find("select").bind("change",detail_change_fn);
								$("#load_div").hide();
								$("#add_to_backprocket").hide();
							} 
						});
					});
					
					jQuery("a.addcart").click(function(el){
						var _target = jQuery(el.target)||jQuery(el);
						if (_target.attr("disabled") != "" && _target.attr("disabled") == "true") return false;
						
						$("#add_to_backprocket").hide();
						if (jQuery("select[@name=\'size\']").val() != "")
						{
							if (jQuery("select[@name=\'quantity\']").val() != ""){
								jQuery("#add_tocart_error").hide();
								jQuery("form[name=\'productform\']").submit();
							}else{
								jQuery("#add_tocart_error").html("<span class=\"error\">Please select quantity.</span>");
								jQuery("#add_tocart_error").show();
							}
						}
						else
						{
							jQuery("#add_tocart_error").html("<span class=\"error\">Please select size.</span>");
							jQuery("#add_tocart_error").show();
						}
						
						return false;
					});
					
					if ($("#product_detail #detailtab .cons .hdproduct").height()>275)
					{
						$("#product_detail #detailtab .cons").css({"height":"275px","overflow":"auto"});
					}else{
						$("#product_detail #detailtab .cons").css({"height":"auto","overflow":"auto"});
					}
				});</script>
				<a href="#" title="" id="slip" class="addto">ADD TO WISHLIST</a> <a href="javascript:void(0);" title="" id="share_this_product" class="share_this_product">SHARE THIS PRODUCT</a><a id="askquestion" class="iframe" title="ask question" href="'.$this->Environment->base.'feedback.html">ASK A QUESTION</a>
			</div>' . ((!isset($colourHTML) || $colourHTML == '') ? '' : '
			<p class="select_color"><strong>SELECT COLOR</strong>: 
			'.$colourHTML.'
			</p>
			<p class="skin">
				<label id="detail_size"><strong>SIZE</strong>: <select id="size" name="size">
						'.$sizeHTML.'
					</select>
				</label>') . ((isset($colourHTML) && $colourHTML != '') ? '
			<span class="size_chart"><img src="images/icon_size_chart.gif" alt="" /> <a href="Size_chart.html" class="iframe3" title="">size chart</a></span>' : '');
			
			foreach ($objRd['attribute'] as $arrAttributeItem)
			{
				if ($arrAttributeItem['colour'] == $default_color && $arrAttributeItem['size'] == $default_size)
				{
					$currentStock = intval($arrAttributeItem['stock']);
					break;
				}
			}
					
			$strQuantityHtml = '';
			
			if (!is_null($currentStock))
			{
				if (intval($currentStock) <= 0)
					$strQuantityHtml = '<label id="detail_quantity"></label>';
				else
				{
					$strQuantityHtml = '<label id="detail_quantity"><strong>QUANTITY</strong>: <select id="quantity" name="quantity">';
					if (intval($currentStock) >= 10)
						$strQuantityHtml .= '<option value="1" selected="selected">1</option>
							<option value="2">2</option>
							<option value="3">3</option>
							<option value="4">4</option>
							<option value="5">5</option>
							<option value="6">6</option>
							<option value="7">7</option>
							<option value="8">8</option>
							<option value="9">9</option>
							<option value="10">10</option>';
					else 
					{
						for ($i=1;$i<=intval($currentStock);$i++)
						{
							$strQuantityHtml .= '<option value="' . $i . '">' . $i . '</option>';
						}
					}
					
					$strQuantityHtml .= '</select></label>';
				}
			}
			else
			{
				$strQuantityHtml = '<label id="detail_quantity"></label>';
			}
			
			$strAddToCartInfo = "";
			if (isset($_GET['add_tocart']) && $_GET['add_tocart'])
			{
				switch ($_GET['add_tocart'])
				{
					case 'success':
						$strAddToCartInfo = '<p id="add_tocart_success"><span class="success">Item(s) added to your cart</span></p>';
						break;
					case 'failure':
						if ($this->Input->get('stock') !== false)
							$strAddToCartInfo = '<p id="add_tocart_faliure"><span class="error">The item(s) is already in your cart. If you\'d like to add more, please go to shopping cart and update the quantity.</span></p>';
						break;
					default:
						break;
				}
			}
			
			$strHTML .= $strQuantityHtml . '</p>' . (((intval($currentStock) <= 0 && !is_null($currentStock)) || !isset($colourHTML) || $colourHTML == '') ? '<span class="error">Out of stock. <a href="mailto:info@daftshopping.com?subject=Out of stock-'.$objRd["skuid"].'-' . $objRd["name"] . '" title="email me" style="color:White;"><u>Email me</u></a> when this item becomes available.</span>' : '') . (($objRd['is_wrapping']) ? '<p class="wrapping"><input type="checkbox" name="gift_wrapping" value="1" id="" /> I want <a title="" class="wrapping_link">'.$objRd['gwTitle'].'</a> ('.$this->obj_currency->change_order($objRd['gwPrice']).')<input type="hidden" name="gwPrice" value="' . $objRd['gwPrice'] . '" /></p>' : '') . '<p id="add_tocart_error" style="display:none;"><span class="error">Please select the size.</span></p><p id="shipping_cart_none_error" style="display:none;"><span class="error">Your shopping cart is empty. </span></p><p id="add_to_backprocket" style="display:none;"><span class="success">This item has been added to your wishlist. <a href="backpocket.html" tilte="Backpocket">View here</a>.</span></p>' . $strAddToCartInfo . '
			<p class="' . (((intval($currentStock) <= 0 && !is_null($currentStock)) || !isset($colourHTML) || $colourHTML == '') ? 'submits_continue' : 'submits') . '"><a href="#" title="ADD TO CART" class="addcart"' . (($is_out_of_stock) ? ' disabled="true"': '') . '>ADD TO CART</a><a href="./shoppingcart.html" title="CHECKOUT" class="checkout"' . (($is_out_of_stock) ? ' disabled="true"': '') . '>CHECKOUT</a></p>

			<div id="gift_wrapping" class="none">
				<span class="icon_tip"></span>
				<img src="'.$objRd['gwImg'].'" alt="'.$objRd['gwTitle'].'" />
			</div> <!-- gift_wrapping end -->
			<div id="share_product" class="none">
				<div class="cons">
					<span class="icon_tip"></span>
					<ul>
						<li><a href="http://www.facebook.com/sharer.php?u='.$shareurl.'" title="Facebook" target="_blank"><img src="images/sociable/share_facebook.gif" alt="Facebook" /></a></li>
						<li><a href="http://twitthis.com/twit?url='.$shareurl.'" title="Twitter" target="_blank"><img src="images/sociable/share_twitter.gif" alt="Twitter" /></a></li>
						<li><a href="http://del.icio.us/post?url='.$shareurl.'&title=Men\'s clothing delivered all over China" title="Delicious" target="_blank"><img src="images/sociable/share_delicious.gif" alt="Delicious" /></a></li>
						<li><a href="http://digg.com/submit?phase=2&url='.$shareurl.'" title="Digg" target="_blank"><img src="images/sociable/share_digg.gif" alt="Digg"/></a></li>
						<li><a href="Tell_friend.html" class="iframe2" title="E-mail"><img src="images/sociable/icon_email.gif" alt="E-mail" /></a></li>
					</ul>
				</div>
			</div>
		</div>
	</div>
	</form>
</div>		
		';

		return $strHTML;
	}
	
	public function getProductDetailPage()
	{
		$rdArray_related = array();
		
		$id    = $_GET['id'];
		$_id_category = $_GET['category'];
		$this->import('Database');
		$obj_category = $this->Database->prepare("SELECT * FROM `tl_taxonomy` WHERE `id`=?")
										->execute($_id_category, time(), time());
										
		if ($obj_category->numRows < 1)
		{
			header("Location:id-4o4-page.html");exit;
		}
		
		$sql   = 'SELECT product_catalog.*,tl_taxonomy.name as categoryName,catalog_wrapping.title as gwTitle,catalog_wrapping.img as gwImg,catalog_wrapping.price as gwPrice,tl_catalog_attribute.id_catalog,tl_catalog_attribute.id_color,tl_catalog_attribute.id_size,tl_catalog_attribute.catalog_stock   
				  FROM `product_catalog` 
				  INNER JOIN `tl_taxonomy` ON product_catalog.category=tl_taxonomy.id 
				  INNER JOIN `catalog_wrapping` ON product_catalog.wrapping=catalog_wrapping.id 
				  INNER JOIN `tl_catalog_attribute` ON `tl_catalog_attribute`.id_catalog=`product_catalog`.id 
				  WHERE product_catalog.id=' . $id .
				  ' ORDER BY `tl_catalog_attribute`.id_color ASC, `tl_catalog_attribute`.id_size ASC';
		$objRd = $this->Database->execute($sql);
		
		if ($objRd->numRows < 1)
		{
			header("Location:id-4o4-page.html");exit;
		}
		
		$index = 0;
		while ($objRd->next())
		{
			if ($index == 0)
			{
				$rdArray['id'] 			= $objRd->id;
				$rdArray['pid'] 		= $objRd->pid;
				$rdArray['category'] 	= $objRd->category;
				$rdArray['categoryName']= $objRd->categoryName;
				$rdArray['name'] 		= $objRd->name;
				$rdArray['overview'] 	= $objRd->overview;
				$rdArray['description'] = $objRd->description;
				$rdArray['price'] 		= $objRd->price;
				$rdArray['wasprice'] 		= $objRd->wasprice;
				$rdArray['skuid'] 		= $objRd->skuid;
				$rdArray['programe'] 	= $objRd->programe;
				$rdArray['sales'] 		= $objRd->sales;
				//$rdArray['size'] 		= $objRd->size;
				$rdArray['related_skuid'] = $objRd->related_skuid;
				$rdArray['gwTitle'] 	= $objRd->gwTitle;
				$rdArray['gwImg'] 		= $objRd->gwImg;
				$rdArray['gwPrice'] 	= $objRd->gwPrice;
				$rdArray['tags'] 		= $objRd->tags;
				$rdArray['img'] 		= $objRd->img;
				$rdArray['is_wrapping'] = $objRd->is_wrapping;
				$rdArray['published'] = $objRd->published;
				
				$rdArray_related['id'] 			= $objRd->id;
				//$rdArray_related['pid'] 		= $objRd->pid;
				$rdArray_related['category'] 	= $objRd->category;
				//$rdArray_related['categoryName']= $objRd->categoryName;
				$rdArray_related['name'] 		= $objRd->name;
				//$rdArray_related['description'] = $objRd->description;
				//$rdArray_related['price'] 		= $objRd->price;
				//$rdArray_related['skuid'] 		= $objRd->skuid;
				//$rdArray_related['related_skuid'] = $objRd->related_skuid;
				//$rdArray_related['gwTitle'] 	= $objRd->gwTitle;
				//$rdArray_related['gwImg'] 		= $objRd->gwImg;
				//$rdArray_related['gwPrice'] 	= $objRd->gwPrice;
				//$rdArray_related['tags'] 		= $objRd->tags;
				$rdArray_related['img'] 		= $objRd->img;
				//$rdArray_related['is_wrapping'] = $objRd->is_wrapping;
			}
			
			/**
			 * Attribute array
			 */
			if (!isset($rdArray['attribute']))
			{
				$rdArray['attribute'] = array();
			}
			
			$rdArray['attribute'][] = array(
				'colour' => $objRd->id_color,
				'size' => $objRd->id_size,
				'stock' => $objRd->catalog_stock
			);
			
			/**
			 * Color array
			 */
			if (!isset($rdArray['colour'][$objRd->id_color][$objRd->id_size]))
			{
				$rdArray['colour'][$objRd->id_color][$objRd->id_size] = array();
			}
			
			$rdArray['colour'][$objRd->id_color][$objRd->id_size][] = $objRd->catalog_stock;					
		}		
		
		$sessionid = session_id();
		
		if (!isset($_SESSION['RELATED_PRODUCTS']) || !is_array($_SESSION['RELATED_PRODUCTS']))
		{
			$_SESSION['RELATED_PRODUCTS'] = array();
			
			$_SESSION['RELATED_PRODUCTS'][$sessionid] = array();
			array_push($_SESSION['RELATED_PRODUCTS'][$sessionid], $rdArray_related);
		}			
		else
		{
			if (!isset($_SESSION['RELATED_PRODUCTS'][$sessionid]) || !is_array($_SESSION['RELATED_PRODUCTS'][$sessionid]))
			{
				$_SESSION['RELATED_PRODUCTS'][$sessionid] = array();
				array_push($_SESSION['RELATED_PRODUCTS'][$sessionid], $rdArray_related);
			}
			else
			{
				if (in_array($rdArray_related, $_SESSION['RELATED_PRODUCTS'][$sessionid]))
				{
					$key = array_search($rdArray_related, $_SESSION['RELATED_PRODUCTS'][$sessionid]);
					
					unset($_SESSION['RELATED_PRODUCTS'][$sessionid][$key]);
					
					array_push($_SESSION['RELATED_PRODUCTS'][$sessionid], $rdArray_related);
					$_SESSION['RELATED_PRODUCTS'][$sessionid] = array_values($_SESSION['RELATED_PRODUCTS'][$sessionid]);
				}
				else
				{
					if (count($_SESSION['RELATED_PRODUCTS'][$sessionid]) < 20)
						array_push($_SESSION['RELATED_PRODUCTS'][$sessionid], $rdArray_related);
					else
					{
						array_pop($_SESSION['RELATED_PRODUCTS'][$sessionid]);
						array_push($_SESSION['RELATED_PRODUCTS'][$sessionid], $rdArray_related);
					}
				}
			}
		}
		
		return $rdArray;		
	}
	
	public function getColour()
	{
		$dataArray = array();
		$this->import('Database');
		$objRd = $this->Database->execute("SELECT * FROM `catalog_colour` Order by id asc");
		
		while ($objRd->next())
		{
			$dataArray[$objRd->id]['id_colour'] = $objRd->id;
			$dataArray[$objRd->id]['title'] 	= $objRd->title;
			$dataArray[$objRd->id]['img'] 		= $objRd->img;
		}
		return $dataArray;
	}
	
	public function getSize()
	{
		$dataArray = array();
		$this->import('Database');
		$objRd = $this->Database->execute("SELECT * FROM `catalog_size` Order by id asc");
		
		while ($objRd->next())
		{
			$dataArray[$objRd->id]['size'] = $objRd->size;
		}
		return $dataArray;
	}	

	public function getTag()
	{
		$dataArray = array();
		$this->import('Database');
		$objRd = $this->Database->execute("SELECT * FROM `catalog_tags` Order by id asc");
		
		while ($objRd->next())
		{
			$dataArray[$objRd->id]['tag'] = $objRd->tag;
		}
		return $dataArray;
	}
	
	public function getBreadcrumb()
	{
		$objRd = $this->getProductDetailPage();
		
		$strHTML = '<div class="path"><a href="./" title="">HOME</a> &nbsp;&nbsp;&gt;&nbsp;&nbsp; <a href="./?type=all&category='.$objRd['category'].'" title="'.$objRd['categoryName'].'">'.$objRd['categoryName'].'</a> &nbsp;&nbsp;&gt;&nbsp;&nbsp; '.$objRd['name'].'</div>';
		
		return $strHTML;
	}

	private function getShippings($programe_id='1')
	{
		$this->import('Database');
		if (is_null($programe_id) || $programe_id == '' || $programe_id == 0)
		{
			$objRd = $this->Database->prepare("SELECT `tl_shippings`.`pid` FROM `tl_shippings` LIMIT 1")
									->execute(time(),time());
			$programe_id = $objRd->pid;
		}
		$arr_shippings = array();		
		
		$objRd = $this->Database->prepare("SELECT ship.*, area.`name` AS area_name
										FROM tl_shippings AS ship
										INNER JOIN tl_areas AS area ON ship.area=area.id 
										WHERE ship.pid=?
										ORDER BY area.`sort` ASC, ship.`sort` ASC")
								->execute($programe_id,time(),time());
		
		$_shipping_html = "<table>
							<thead>
								<tr>
								  <th>SHIP TO</th>
								  <th></th>
								  <th>COSTS</th>
								  <th>WITH ANOTHER ITEM</th>
								</tr>
							</thead>
							<tbody>";
		if ($objRd->numRows >= 1)
		{
			while ($objRd->next())
			{
				$arr_shippings[$objRd->id] = array(
					'name' => $objRd->name,
					'des' => $objRd->des,
					'price' => $objRd->price,
					'area_name' => $objRd->area_name,
					'images' => $objRd->images,
					'firstprice' => $this->obj_currency->change_order($objRd->firstprice),
					'continueprice' => $this->obj_currency->change_order($objRd->continueprice),
				);
			}
			
			foreach ($arr_shippings as $arr_ship)
			{
				$_shipping_html .= '<tr><th>'.$arr_ship['area_name'].'</th><td>'.$arr_ship['des'].'</td><td>'.$arr_ship['firstprice'].'</td><td>'.$arr_ship['continueprice'].'</td></tr>';
			}
		}
		$_shipping_html .= "</tbody>
</table><p><a href=\"shipping_chart.html\" class=\"iframe4\" id=\"more_shipping_detail\" title=\"MORE DETAILS\">MORE DETAILS</a></p>";
		
		return $_shipping_html;
	}
	
}

$objGetRd = new GetProductDetail();
$objGetRd->run();

?>